<template>
  <el-drawer
    title="消费扣款"
    :visible="deductionExtraction"
    show-close
    :before-close="handleClose"
    :wrapperClosable="true"
    class="drawer-style"
  >
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
      <el-form-item>
        <div class="text-div">
          <div class="title-div"></div>
          <div class="title-text">创建订单</div>
        </div>
      </el-form-item>
      <el-form-item
        prop="enterpriseValue"
        label="选择油站"
        class="extraction-style"
        size="small"
      >
        <el-select
          v-model="ruleForm.enterpriseValue"
          placeholder="请选择"
          style="width: 400px"
          @change="changeListWithOil"
          :placeholder="
            enterpriseList.length === 1
              ? enterpriseList[0].stationName
              : '请选择'
          "
        >
          <el-option
            v-for="(item, index) in enterpriseList"
            :key="index"
            :label="item.stationName"
            :value="item.stationId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="withOilValue"
        label="员工选择"
        class="extraction-style"
        size="small"
      >
        <el-select
          v-model="ruleForm.withOilValue"
          placeholder="请选择"
          style="width: 400px"
          @change="changeList"
        >
          <el-option
            v-for="item in listWithOilDatas.length
              ? listWithOilDatas
              : listWithOilData"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        prop="gunListValue"
        label="选择油枪"
        class="extraction-style"
        size="small"
      >
        <el-select
          v-model="ruleForm.gunListValue"
          placeholder="请选择"
          style="width: 400px"
          @change="changeOil"
        >
          <el-option
            v-for="item in gunList"
            :key="item.gunName"
            :label="item.gunName"
            :value="`${item.oil.oilName}-${item.oil.oilClass}-${item.gunName}`"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="extraction-style">
        <p class="fone-text">油品</p>
        <p>{{ ruleForm.oilName }}</p>
      </el-form-item>
      <el-form-item
        prop="amountPayable"
        label="应付金额（元）"
        class="extraction-style"
        size="small"
      >
        <el-input
          type="number"
          class="control-amountPayable"
          v-model="ruleForm.amountPayable"
          style="width: 400px"
          placeholder="请输入"
          maxlength="12"
          @input="changeInput"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <div class="text-div">
          <div class="title-div"></div>
          <div class="title-text">支付设置</div>
        </div>
      </el-form-item>
      <el-form-item
        label="支付方式"
        prop="payment"
        class="extraction-style"
        size="small"
      >
        <el-select
          :placeholder="
            paymentList.length === 1 ? paymentList[0].name : '请选择'
          "
          v-model="ruleForm.payment"
          style="width: 400px"
          @change="changePayment"
        >
          <el-option
            v-for="item in paymentList"
            :key="item.id"
            :label="item.name"
            :value="item.balance"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="extraction-style">
        <p class="fone-text">{{ ruleForm.payment[0] }} 余额（元）</p>
        <p>{{ ruleForm.storedAmt }}</p>
      </el-form-item>
      <el-form-item
        label="参与立减活动"
        prop="subtraction"
        class="extraction-switch"
      >
        <el-switch
          @change="changeSwitchGo"
          v-model="ruleForm.subtraction"
        ></el-switch>
      </el-form-item>
      <el-form-item label="使用优惠券" prop="useThe" class="extraction-switch">
        <el-switch @change="changeSwitch" v-model="ruleForm.useThe"></el-switch>
      </el-form-item>
      <el-form-item
        class="extraction-style"
        size="small"
        v-show="ruleForm.useThe"
      >
        <el-select
          v-model="ruleForm.couponValue"
          placeholder="请选择"
          style="width: 400px"
          @change="changeCoupon"
        >
          <el-option
            v-for="item in couponList"
            :key="item.couponUserId"
            :label="item.issueName"
            :value="item.couponUserId"
          >
            <span style="float: left">{{ item.issueName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
              item.couponUserId
            }}</span></el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item class="extraction-style">
        <p class="fone-text">实付金额（元）</p>
        <p>{{ ruleForm.actualAmount }}</p>
      </el-form-item>
      <el-form-item
        label="支付密码"
        prop="password"
        class="extraction-style"
        size="small"
      >
        <el-input
          v-model="ruleForm.password"
          style="width: 400px"
          placeholder="请输入"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item class="extraction-button" size="small">
        <el-button @click="exitOut">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确认</el-button
        >
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script>
import { listWithOil, update, create, pay } from "@/api/customer/info";
export default {
  name: "Deduction",
  props: {
    deductionExtraction: {
      type: Boolean,
      default: false,
    },
    enterpriseList: {
      default: () => [],
    },
    listWithOilDatas: {
      default: () => [],
    },
    consumerId: {
      default: "",
    },
    stationIds: {
      default: "",
    },
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        if (this.stationIds) {
          callback();
        } else {
          callback(new Error("请选择油站"));
        }
      } else {
        callback();
      }
    };
    return {
      couponId: null,
      couponUser: null,
      // 员工列表
      listWithOilData: [],
      // 油枪列表
      gunList: [],
      // 支付方式列表
      paymentList: [],
      // 优惠劵列表
      couponList: [],

      // 优惠劵
      //订单号，创建订单接口返回
      orderNo: null,
      //优惠卷no，创建订单接口返回
      couponNo: null,
      //优惠卷id，创建订单接口返回
      couponUserId: null,

      // 表单数据
      ruleForm: {
        // 油站选择值
        enterpriseValue: "",
        // 员工选择值
        withOilValue: "",
        // 油枪选择值
        gunListValue: "",
        // 油品名称
        oilName: "--",
        // 应付金额
        amountPayable: "",
        // 支付方式值
        payment: "",
        // 余额
        balance: "",
        // 立减活动
        subtraction: true,
        // 使用优惠券
        useThe: true,
        // 密码
        password: null,
        // 卡余额
        storedAmt: "---",
        // 选择优惠劵选择值
        couponValue: "",
        // 实付金额
        actualAmount: "---",
      },
      rules: {
        enterpriseValue: [{ validator: validatePass, trigger: "change" }],
        // enterpriseValue: [
        //   { required: true, message: "请选择油站", trigger: "change" },
        // ],
        withOilValue: [
          { required: true, message: "请选择员工", trigger: "change" },
        ],
        gunListValue: [
          { required: true, message: "请选择油枪", trigger: "change" },
        ],
        amountPayable: [
          {
            required: true,
            type: "string",
            trigger: "blur",
            message: "请输入应付金额",
          },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "应付金额仅支持两位小数",
          },
        ],
        // payment: [
        //   { required: true, message: "请选择支付方式", trigger: "change" },
        // ],
        subtraction: [
          { required: true, message: "未参与立减活动", trigger: "change" },
        ],
        useThe: [
          { required: true, message: "未使用优惠卷", trigger: "change" },
        ],
        // password:[{ required: true, message: '请输入密码', trigger: 'change' }],
      },
    };
  },
  created() {},
  methods: {
    // 选择了油站
    changeListWithOil() {
      // 员工列表
      this.listWithOilData = [];
      // 员工选择值
      this.ruleForm.withOilValue = "";
      // 油枪列表
      this.gunList = [];
      // 油枪选择值
      this.ruleForm.gunListValue = "";
      // 油品名称
      this.ruleForm.oilName = "";
      // 应付金额
      this.ruleForm.amountPayable = "";
      // 支付方式列表
      this.paymentList = [];
      // 支付方式值
      this.ruleForm.payment = "";
      // 卡余额
      this.ruleForm.storedAmt = "";
      // 实付金额
      this.ruleForm.actualAmount = "---";
      // 优惠劵列表
      this.couponList = [];
      // 选择优惠劵选择值
      this.ruleForm.couponValue = "";

      // 获取员工
      listWithOil({
        stationId: this.ruleForm.enterpriseValue,
      }).then((res) => {
        this.listWithOilData = res.data;
        // console.log("油站获取员工列表", res);
      });
      // console.log("选择油站", this.ruleForm.enterpriseValue,this.enterpriseList[0].stationName);
    },

    // 选择了员工
    changeList() {
      // 油枪列表
      this.gunList = [];
      // 油枪选择值
      this.ruleForm.gunListValue = "";
      // 油品名称
      this.ruleForm.oilName = "";
      // 应付金额
      this.ruleForm.amountPayable = "";
      // 支付方式列表
      this.paymentList = [];
      // 支付方式值
      this.ruleForm.payment = "";
      // 卡余额
      this.ruleForm.storedAmt = "";
      // 实付金额
      this.ruleForm.actualAmount = "---";
      // 优惠劵列表
      this.couponList = [];
      // 选择优惠劵选择值
      this.ruleForm.couponValue = "";

      if (this.listWithOilDatas.length) {
        this.listWithOilDatas.forEach((item) => {
          if (item.userId === this.ruleForm.withOilValue) {
            this.gunList = item.gunList;
          }
        });
      } else {
        this.listWithOilData.forEach((item) => {
          if (item.userId === this.ruleForm.withOilValue) {
            this.gunList = item.gunList;
          }
        });
      }

      // console.log("选择了员工", this.gunList);
    },

    // 选择了油枪
    changeOil() {
      // 应付金额
      this.ruleForm.amountPayable = "";
      // 支付方式列表
      this.paymentList = [];
      // 支付方式值
      this.ruleForm.payment = "";
      // 卡余额
      this.ruleForm.storedAmt = "";
      // 实付金额
      this.ruleForm.actualAmount = "---";
      // 优惠劵列表
      this.couponList = [];
      // 选择优惠劵选择值
      this.ruleForm.couponValue = "";

      //  若是汽油，则显示“汽油卡”和“车队卡”；
      //  若是柴油，则显示“柴油卡”和“车队卡”，
      //  LNG、CNG同理；{汽油，柴油，LNG，CNG}

      this.ruleForm.oilName = this.ruleForm.gunListValue.split("-")[0];
      console.log("选择了油枪", this.ruleForm.gunListValue);

      if (this.ruleForm.gunListValue.split("-")[1] === "汽油") {
        this.paymentList = [
          //{ name: "电子卡", balance: ["汽油卡", "dzk"], id: 1 },
          { name: "汽油卡", balance: ["汽油卡", "dzk"], id: 2 },
          // { name: "车队卡", balance: ["车队卡", "cdk"], id: 3 },
        ];
      } else if (this.ruleForm.gunListValue.split("-")[1] === "柴油") {
        this.paymentList = [
          //{ name: "电子卡", balance: ["柴油卡", "dzk"], id: 1 },
          { name: "柴油卡", balance: ["柴油卡", "dzk"], id: 2 },
          // { name: "车队卡", balance: ["车队卡", "cdk"], id: 3 },
        ];
      } else if (this.ruleForm.gunListValue.split("-")[1] === "LNG") {
        this.paymentList = [
          //{ name: "电子卡", balance: ["LNG卡", "dzk"], id: 1 },
          { name: "LNG卡", balance: ["LNG卡", "dzk"], id: 2 },
          // { name: "车队卡", balance: ["车队卡", "cdk"], id: 3 },
        ];
      } else if (this.ruleForm.gunListValue.split("-")[1] === "CNG") {
        this.paymentList = [
          //{ name: "电子卡", balance: ["CNG卡", "dzk"], id: 1 },
          { name: "CNG卡", balance: ["CNG卡", "dzk"], id: 2 },
          // { name: "车队卡", balance: ["车队卡", "cdk"], id: 3 },
        ];
      }
      // console.log("选择了油枪", this.ruleForm.gunListValue);
    },

    // 选择了支付方式
    changePayment() {
      this.Judgment();
    },

    // 判断现在是有没有订单号没有就创建有就更新
    Judgment() {
      const datas = this.listWithOilDatas.length
        ? this.stationIds
        : this.ruleForm.enterpriseValue;
      if (
        this.ruleForm.gunListValue.split("-")[2] &&
        this.ruleForm.withOilValue &&
        this.ruleForm.amountPayable.trim() &&
        datas
      ) {
        if (this.orderNo) {
          this.updateInif();
        } else {
          this.createPots();
        }
      }
      // gunName: this.ruleForm.gunListValue.split("-")[2], //油枪名称
      //   oilPersonnel: this.ruleForm.withOilValue, //加油员id
      //   receivableAmt: this.ruleForm.amountPayable, //应付金额
      //   stationId: this.ruleForm.enterpriseValue, //油站id
    },

    // 创建订单
    createPots() {
      const station = this.listWithOilDatas.length
        ? this.stationIds
        : this.ruleForm.enterpriseValue;
      const data = {
        appType: "1", //固定写死1
        orderOriginType: "4", //固定写死4
        gunName: this.ruleForm.gunListValue.split("-")[2], //油枪名称
        oilPersonnel: this.ruleForm.withOilValue, //加油员id
        // payType: this.ruleForm.payment[1], //支付方式，dzk-电子啊看，cdk-车队卡
        payType: "dzk", //支付方式，dzk-电子啊看，cdk-车队卡
        receivableAmt: this.ruleForm.amountPayable, //应付金额
        stationId: station, //油站id
        utmSource: 9, //固定写死9
        enableDiscount: this.ruleForm.subtraction, //是否参与优惠
        enableCoupon: this.ruleForm.useThe, //是否使用优惠卷
        password: this.ruleForm.password, //密码
        consumerId: this.consumerId, //会员id
      };
      // console.log("console.log", data);
      create(data).then((res) => {
        this.ruleForm.storedAmt = res.data.storedAmt;
        this.ruleForm.actualAmount = res.data.amt;
        this.couponList = res.data.couponList;
        //订单号，创建订单接口返回
        this.orderNo = res.data.orderNo;
        this.couponUserId = res.data.couponUserId;
        this.ruleForm.couponValue = res.data.couponUserId;
        // console.log("创建订单", res);
      });
    },

    // 选择了优惠劵
    changeCoupon() {
      this.couponList.forEach((item) => {
        if (this.ruleForm.couponValue === item.couponUserId) {
          this.couponUser = item.couponNo;
          this.couponId = item.couponUserId;
        }
      });
      // couponNo: this.couponUser, //优惠卷no，创建订单接口返回
      //   couponUserId: this.couponId, //优惠卷id，创建订单接口返回
      this.Judgment();
    },

    updateInif() {
      // 更新接口
      const data = {
        appType: "1", //固定写死1
        orderOriginType: "4", //固定写死4
        gunName: this.ruleForm.gunListValue.split("-")[2], //油枪名称
        oilPersonnel: this.ruleForm.withOilValue, //加油员id
        // payType: this.ruleForm.payment[1], //支付方式，dzk-电子啊看，cdk-车队卡
        payType: "dzk", //支付方式，dzk-电子啊看，cdk-车队卡
        receivableAmt: this.ruleForm.amountPayable, //应付金额
        stationId: this.listWithOilDatas.length
          ? this.stationIds
          : this.ruleForm.enterpriseValue, //油站id
        utmSource: 9, //固定写死9
        enableDiscount: this.ruleForm.subtraction, //是否参与优惠
        enableCoupon: this.ruleForm.useThe, //是否使用优惠卷
        password: this.ruleForm.password, //密码
        consumerId: this.consumerId, //会员id
        orderNo: this.orderNo, //订单号，创建订单接口返回
        couponNo: this.couponUser, //优惠卷no，创建订单接口返回
        couponUserId: this.couponId, //优惠卷id，创建订单接口返回
      };
      update(data).then((res) => {
        this.ruleForm.storedAmt = res.data.storedAmt;
        this.ruleForm.actualAmount = res.data.amt;
        this.couponList = res.data.couponList;
        //订单号，创建订单接口返回
        this.orderNo = res.data.orderNo;
        this.couponUserId = res.data.couponUserId;
        this.ruleForm.couponValue = res.data.couponUserId;
        // console.log("更新接口", res);
      });
    },

    // 推出抽屉
    handleClose() {
      this.$refs.ruleForm.clearValidate();
      this.resettingData();
      this.$emit("update:deductionExtraction", false);
    },

    // 是否参与优惠活动
    changeSwitchGo() {
      this.Judgment();
    },

    // 是否使用优惠眷
    changeSwitch() {
      this.Judgment();
    },

    // 输入金额
    changeInput() {
      this.$refs.ruleForm.validateField("amountPayable", (res) => {
        if (!res) {
          this.Judgment();
        }
      });
    },
    // 表单验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = {
            orderNo: this.orderNo, //订单号，创建订单接口返回
            couponUserId: this.ruleForm.couponValue, //优惠卷id，创建订单接口返回
            password: this.ruleForm.password, //密码
            consumerId: this.consumerId, //会员id
            stationId: this.ruleForm.enterpriseValue, //油站id
          };
          pay(data).then(async (res) => {
            this.open(res.data);
            this.handleClose();
            console.log("验证成功！", res);
          });
          console.log("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 重置数据
    resettingData() {
      // 清空数据
      // 员工列表
      this.listWithOilData = [];
      // 油枪列表
      this.gunList = [];
      // 支付方式列表
      this.paymentList = [];
      // 优惠劵列表
      this.couponList = [];
      // 优惠劵
      //订单号，创建订单接口返回
      this.orderNo = null;
      //优惠卷no，创建订单接口返回
      this.couponNo = null;
      //优惠卷id，创建订单接口返回
      this.couponUserId = null;
      // 表单数据
      this.ruleForm = {
        // 油站选择值
        enterpriseValue: "",
        // 员工选择值
        withOilValue: "",
        // 油枪选择值
        gunListValue: "",
        // 油品名称
        oilName: "--",
        // 应付金额
        amountPayable: null,
        // 支付方式值
        payment: "",
        // 余额
        balance: "",
        // 立减活动
        subtraction: true,
        // 使用优惠券
        useThe: true,
        // 密码
        password: null,
        // 卡余额
        storedAmt: "---",
        // 选择优惠劵选择值
        couponValue: "",
        // 实付金额
        actualAmount: "---",
      };
    },

    // 点击取消
    exitOut() {
      this.handleClose();
    },

    open(data) {
      this.$message({
        message: data,
        type: "success",
      });
    },
  },
};
</script>
<style>
.fone-text {
  font-weight: bold;
  color: #606266;
}
.text-div {
  margin-right: 20px;
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-left: 20px;
}
.title-text {
  margin-left: 5px;
  font-size: 17px;
  font-weight: bold;
}
.title-div {
  width: 4px;
  height: 20px;
  background-color: #ffbb00;
}
.extraction-button {
  width: 400px;
  margin: 0px 20px;
  padding: 30px 0px;
  display: flex;
  flex-direction: row;
  justify-content: right;
}
.extraction-switch {
  padding: 20px 20px 0px 20px;
}
.el-form-item__label {
  width: 180px;
  text-align: start;
}
.el-drawer__body {
  overflow: auto;
}
.extraction-style {
  padding: 20px 20px 0px 20px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.control-amountPayable input::-webkit-outer-spin-button,
.control-amountPayable input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
.control-amountPayable input[type="number"] {
  -moz-appearance: textfield;
}
</style>
